import axios from 'axios';
import {
  ElLoading
} from 'element-plus';
import {
  getToken
} from '@/utils/index.js';
import 'element-plus/dist/index.css';

const instance = axios.create({
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// Loading类
class Loading {
  constructor() {
    this.loadingInstance = null;
    this.counter = 0;
  }

  // 显示loading
  show() {
    if (this.counter === 0) {
      this.loadingInstance = ElLoading.service({
        fullscreen: true,
        lock: true,
        text: '加载中...',
        // spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        delay: 500,
        duration: 2000 // 显示时间为2秒
      });
    }
    this.counter++;
  }

  // 隐藏loading
  hide() {
    this.counter--;
    if (this.counter === 0 && this.loadingInstance) {
      this.loadingInstance.close();
    }
  }
}

const loading = new Loading();

instance.interceptors.request.use(
  (config) => {
    if (config) {
      // 增加token 没有token 跳转到登录页
      console.log(getToken(), 'token');
      const token = 'test';
      config.headers.Authorization = `Bearer ${token}`;
      localStorage.setItem('token', token);
    }
    loading.show(); // 显示loading
    return config;
  },
  (error) => {
    loading.hide();
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    loading.hide();
    return response;
  },
  (error) => {
    loading.hide();
    if (error.response) {
      // 根据状态码进行错误处理
      switch (error.response.status) {
        case 401:
          // 用户未登录，跳转到登录页
          window.location.href = '/login';
          break;
        case 403:
          // 用户无权限访问，跳转到错误页
          window.location.href = '/error';
          break;
        case 404:
          // 请求的资源不存在，跳转到错误页
          window.location.href = '/error';
          break;
        default:
          // 其他错误，跳转到错误页
          window.location.href = '/error';
          break;
      }
    } else {
      // 请求超时或网络错误 超时提示 网络错误提示
      if (
        error.code === 'ECONNABORTED' ||
        error.message.indexOf('Network Error') > -1
      ) {
        ElLoading.service({
          fullscreen: true,
          lock: true,
          text: '请求超时或网络错误，稍后尝试',
          // spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        // 3s后关闭
        setTimeout(() => {
          ElLoading.service().close();
        }, 3000);
      }
    }
    return Promise.reject(error);
  }
);

export default {
  get(url, config = {}) {
    return instance.get(url, config);
  },
  post(url, data = {}, config = {}) {
    return instance.post(url, data, config);
  },
  put(url, data = {}, config = {}) {
    return instance.put(url, data, config);
  },
  delete(url, config = {}) {
    return instance.delete(url, config);
  }
};